package com.kantboot.business.ac.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.kantboot.business.ac.domain.ao.YrApiProductAO;
import com.kantboot.business.ac.domain.ao.YrApiProductTypeAO;
import com.kantboot.business.ac.domain.dto.YrApiToRequestDTO;
import com.kantboot.business.ac.service.IBusAcYrApiService;
import com.kantboot.system.setting.service.ISysSettingService;
import com.kantboot.util.common.exception.BaseException;
import io.netty.util.internal.StringUtil;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class BusAcYrApiServiceImpl implements IBusAcYrApiService {

    @Resource
    private ISysSettingService settingService;

    @Override
    public String getYrApiPrefix() {
        String value = settingService.getValue("acProjectApi", "yrApiPrefix");
        // 如果结尾不是/，则加上/
        if (!value.endsWith("/")) {
            value += "/";
        }
        return value;
    }

    @Override
    public String generateRequestParam(Map<String,Object> map) {
        String userid = settingService.getValue("acProjectApi", "yrApiUserid");
        // 将object转换成map
        if (map == null) {
            map = new HashMap<>();
        }
        // 将userid放入map中
        map.put("userid",userid);
        // 将map转换成key=value&key=value的形式
        Set<String> strings = map.keySet();
        // 将set转换为List
        ArrayList<String> keyList = new ArrayList<>(strings);
        // 将keyList按照字典序排序
        keyList.sort(String::compareTo);

        StringBuilder stringBuilder = new StringBuilder();
        for (String string : keyList) {
            if (map.get(string) == null) {
                continue;
            }
            stringBuilder.append(string).append("=").append(map.get(string)).append("&");
        }
        stringBuilder.deleteCharAt(stringBuilder.length()-1);
        return stringBuilder.toString();
    }

    @Override
    public String generateSign(Map<String,Object> map) {
        String appKey = settingService.getValue("acProjectApi", "yrApiAppKey");
        String paramStr = generateRequestParam(map);
        if(!StringUtil.isNullOrEmpty(paramStr)){
            paramStr+="&";
        }
        paramStr+="apikey="+appKey;
        // 生成签名的字符串
        log.info("生成签名的字符串:{}",paramStr);
        return MD5.create().digestHex(paramStr).toUpperCase();
    }

    @Override
    public String generateRequestParamInRequest(Map<String,Object> map) {
        String paramStr = generateRequestParam(map);
        String sign = generateSign(map);
        if(!StringUtil.isNullOrEmpty(paramStr)){
            paramStr+="&";
        }
        return paramStr+"sign="+sign;
    }

    @SneakyThrows
    @Override
    public Object sendRequest(YrApiToRequestDTO yrApiToRequest) {
        String yrApiPrefix = getYrApiPrefix();
        String uri = yrApiToRequest.getUri();
        Map<String,Object> param = yrApiToRequest.getParam();

        System.err.println(JSON.toJSONString(param));
        // 如果uri以/开头，则去掉/
        if (uri.startsWith("/")) {
            uri = uri.substring(1);
        }

        String yrApiUrl = yrApiPrefix + uri;

        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, generateRequestParamInRequest(param));
        Request request = new Request.Builder()
                .url(yrApiUrl)
                .post(body)
                .addHeader("content-type", "application/x-www-form-urlencoded")
                .build();

        Response response = client.newCall(request).execute();
        String requestResult = response.body().string();
        log.info("请求yrApi的结果:{}",requestResult);

        JSONObject jsonObject = JSON.parseObject(requestResult);
        if(jsonObject.getInteger("errno")!=0){
            throw BaseException.of("yrApiErrorOf"+jsonObject.getInteger("errno"),jsonObject.getString("errmsg"));
        }
        return jsonObject.getList("data", Object.class);
    }

    @Override
    public List<YrApiProductTypeAO> getProductTypeAndCategory() {
        YrApiToRequestDTO yrApiToRequestDTO = new YrApiToRequestDTO();
        yrApiToRequestDTO.setUri("index/typecate");
        yrApiToRequestDTO.setParam(new HashMap<>());
        Object object = sendRequest(yrApiToRequestDTO);
        return JSON.parseArray(JSON.toJSONString(object), YrApiProductTypeAO.class);
    }

    @Override
    public List<YrApiProductAO> getAllProduct() {
        YrApiToRequestDTO yrApiToRequestDTO = new YrApiToRequestDTO();
        yrApiToRequestDTO.setUri("index/product");
        yrApiToRequestDTO.setParam(new HashMap<>());
        Object object = sendRequest(yrApiToRequestDTO);
        return JSON.parseArray(JSON.toJSONString(object), YrApiProductAO.class);
    }
}
